
from datetime import datetime
from pathlib import Path

class LogWriter():
    def __init__(self, log_file=None, fields=[]):
        self.file = None
        if log_file is not None:
            self.add_logfile(log_file)
            self.add_fields(fields)

    def add_logfile(self, file):
        if self.file is not None:
            self.file_handle.close()

        self.file = Path(file)
        self.file.parent.mkdir(exist_ok=True, parents=True)
        if self.file.exists():
            self.file.with_stem(self.file.stem + '_')
        self.file_handle = self.file.open("w")

    def add_fields(self, fields:list, log_time=False):
        text = "Time," if log_time else ""
        for item in fields:
            text += str(item)
            text += ","
        self.file_handle.write(text + "\n")

    def log(self, *msg, echo=False, log_time=False):
        now = datetime.now()
        now = now.strftime("%y/%m/%d %H:%M:%S,") #+ f"{now.timestamp():.3f},"

        text = ""
        for item in msg:
            if isinstance(item, float):
                text += f"{item:.3f},"
            else:
                text += f"{item},"

        if echo:
            print(now + " " + text)

        if log_time:
            self.file_handle.write(now+text + "\n")
        else:
            self.file_handle.write(text + "\n")
        self.file_handle.flush()

    def __del__(self):
        if self.file is not None:
            self.file_handle.close()


